package com.crazy.common.message;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
 * 国际化资源文件加载，支持通配符批量加载
 * @author zhangweiwei
 * @since 2013-10-31下午5:47:54
 */
public class MyReloadableResourceBundleMessageSource extends
		ReloadableResourceBundleMessageSource {
	private static ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
	private static final String suffix = ".properties";
	private static final String PATTERN = "*.properties";
	public void setRegexPatterns(String[] patterns) throws Throwable {
		List<String> list = new ArrayList<String>();
		for (String pattern : patterns) {
			if (pattern.endsWith(PATTERN)) {
				this.add(list, pattern, PATTERN);
			} else if (pattern.endsWith(suffix)) {
				String prefix = pattern.replace(suffix, "");
				list.add(prefix);
			} else if (pattern.endsWith("/*")) {
				this.add(list, pattern, "*");
			} else {
				list.add(pattern);
			}
		}
		String[] baseNames = new String[list.size()];
		this.setBasenames(list.toArray(baseNames));
	}
	private void add(List<String> list, String pattern, String target)
			throws Throwable {
		Resource[] resources = patternResolver.getResources(pattern);
		String prefix = pattern.replace(target, "");
		for (Resource resource : resources) {
			String fileName = resource.getFilename();
			int index = fileName.indexOf(suffix);
			fileName = fileName.substring(0, index);
			list.add(prefix.concat(fileName));
		}
	}
}
